﻿using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ezCloud.Api.Providers
{
    public class SimpleRefreshTokenProvider : IAuthenticationTokenProvider
    {
        private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();
        public static void InvalidateUser(string UserName)
        {
            var tokenList = _refreshTokens.Where(t => t.Value.Identity.Name == UserName).ToList();
            AuthenticationTicket ticket;
            foreach (var token in tokenList)
            {
                _refreshTokens.TryRemove(token.Key, out ticket);
            }
        }
        public void Create(AuthenticationTokenCreateContext context)
        {
            throw new NotImplementedException();
        }

        public void Receive(AuthenticationTokenReceiveContext context)
        {
            throw new NotImplementedException();
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var guid = Guid.NewGuid().ToString();

            // maybe only create a handle the first time, then re-use
            context.Ticket.Properties.Dictionary.Add("refresh_token", guid);
            _refreshTokens.TryAdd(guid, context.Ticket);
            

            // consider storing only the hash of the handle
            context.SetToken(guid);
        }

        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            AuthenticationTicket ticket;
            if (_refreshTokens.TryRemove(context.Token, out ticket))
            {
                var userSessionManager = new Common.UserSessionManager();
                //userSessionManager.InvalidateUserSession();
                context.SetTicket(ticket);
            } 
        }
    }

}
